Ext.define('iMedproplus.controller.Abstract', {
    extend: 'Ext.app.Controller',
    alias: 'controller.abstractcontroller',
    
    adding: false,
    
    init: function() {
        this.callParent(arguments);
        
        var listeners = {
            itemSave: this.onItemSave,
            itemAdd: this.onItemAdd,
            itemUpdate: this.onItemUpdate,
            itemRemove: this.onItemRemove,
            itemStartEdit: this.onItemStartEdit,
            itemCancelEdit: this.onItemCancelEdit
        } 
        this.control(this.abstractConfig.view.xtype, listeners);
    },
    
    onItemAdd: function(rowEditing) {
        rowEditing.cancelEdit();
        
        var item = Ext.create(this.abstractConfig.model, 
            this.abstractConfig.createParams);
            
        this.abstractConfig.store.insert(0, item);
        this.adding = true;
        
        rowEditing.startEdit(0,0);
    },
    
    onItemRemove: function(selectionModel) {
        Ext.Msg.confirm('Uwaga', 'Czy na pewno chcesz usunąć wybrane rekordy?', function(btn){
            if (btn == 'yes'){
                this.abstractConfig.store.remove(selectionModel.getSelection());
            }
        }, this);
    },
    
    onItemUpdate: function() {
        this.adding = false;
    },
    
    onItemCancelEdit: function() {
        if(this.adding){
            this.abstractConfig.store.removeAt(0);
        }
        this.adding = false;
    },
    
    onItemSave: function() {
        var store = this.abstractConfig.store;
        store.sync({
            success: function() {
                store.load();
            },
            failure: function(response) {
                var responseObject = Ext.decode(response.responseText);
                console.log(responseObject);
                Ext.Msg.alert('Uwaga', responseObject.message);
            }
        });
        
        this.adding = false;
    },
    
    onItemStartEdit: function() {
    //console.log('onItemStartEdit not implemented');
    }
    
});